package com.aiju.app;

import android.os.Handler;
import android.os.Looper;

import com.aiju.app.callback.HttpCallback;
import com.aiju.bean.JsonData;
import com.aiju.utils.L;
import com.aiju.utils.T;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: 佐为
 * @date: 2017-03-06 13:52
 * @version: V1.0
 * @Description: 简单网络请求回调
 */
public abstract class SimpleHttpCallback implements HttpCallback {

    private Handler handler = new Handler(Looper.getMainLooper());

    protected JsonData jsonData;

    @Override
    public void onSuccess(String data) {
        for (IResult result : results) {
            result.result(data);
        }
        jsonData = new JsonData(data);
        if (jsonData.isSuccess() || jsonData.isPaySuccess()) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    onDataSuccess(jsonData.getData().toString());
                }
            });
        } else {
            onFailureCallBack(jsonData.getCode(), jsonData.getMsg());
        }
    }

    @Override
    public void onFailure(final int code, final String errorMessage) {
        for (IResult result : results) {
            result.result(errorMessage);
        }
        onFailureCallBack(code, errorMessage);
    }

    private void onFailureCallBack(final int code, final String errorMessage) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                onDataFailure(code, errorMessage);
            }
        });
    }

    /**
     * 成功数据 json里的的key=data
     *
     * @param data
     */
    protected abstract void onDataSuccess(String data);

    /**
     * 数据错误
     */
    protected void onDataFailure(int code, String msg) {
        if (code == 404) {
            T.ToastNetError();
        }else {
            T.ToastShort(msg);
        }
        L.e("failure code:" + String.valueOf(code) + "  msg:" + msg);
    }

    /**
     * 此接口针对拦截日志打印
     */
    public interface IResult {

        void result(String data);
    }

    private List<IResult> results = new ArrayList<>();

    public void addResult(IResult result) {
        results.add(result);
    }

}
